package v1

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"pq/models"
	"pq/service"
	"strconv"
)

type PointCategoryController struct {
	BaseController
}

func (pcc *PointCategoryController) List(){
	//limit,_ := pcc.GetInt("limit",0)
	//skip,_  := pcc.GetInt("skip",models.MAXROWS)
	code := pcc.GetString("code","ROOT")
	cate := new(models.PqTestPointCategory)
	q:= []interface{}{
		-1,
	}
	tm := pcc.GetString("tm")
	cates,count := cate.ListAll(q,code)
	if tm == "deep"{
		cs := service.CategoryService{}
		pcc.Response(cs.GetDeepTree(cates,1),len(cates))
		return
	}
	pcc.Response(cates,count)
}

func (pcc *PointCategoryController) Del()  {
	category := &models.Category{}
	id := pcc.Ctx.Input.Param(":id")
	vid,_ := strconv.Atoi(id)
	_, _ = category.Remove(vid, "pq_test_point_category")
	pcc.Success("Deleted")
}
func (pcc *PointCategoryController) ListByCode()  {
	code := pcc.Ctx.Input.Param(":code")
	slave := models.GetSlaveDb()
	var lists []orm.Params
	var parent models.PqTestPointCategory
	_ = slave.QueryTable("pq_test_point_category").Filter("code", code).One(&parent)
	//slave.QueryTable("pq_test_category").Filter("lft__gte",parent.Lft).Filter("rgt__lte",parent.Rgt).Values(&lists)
	_, _ = slave.Raw(`select  * from pq_test_point_category where state > -1 and lft >= ? and rgt <= ? order by level asc,ordering desc`, parent.Lft, parent.Rgt).Values(&lists)
	pcc.Response(lists,len(lists))
}
func (pcc *PointCategoryController) Store() {
	node := new(models.PqTestPointCategory)
	node.Id,_ = pcc.GetInt("id")
	node.Pid,_ = pcc.GetInt("pid")
	node.Title = pcc.GetString("title")
	node.Image = ""
	node.State = 1
	node.Ordering,_ = pcc.GetInt("ordering",0)
	node.Code  = pcc.GetString("code")
	node.Ordering,_ = pcc.GetInt("ordering")
	node.LibType,_ = pcc.GetInt("lib_type")
	id := 0
	if node.Id > 0 {
		id = node.Id
		master := models.GetMasterDb()
		slave := models.GetSlaveDb()
		var parent models.PqTestPointCategory
		_ = slave.QueryTable("pq_test_point_category").Filter("id", node.Pid).One(&parent)
		_, _ = master.QueryTable("pq_test_point_category").Filter("id", id).Update(orm.Params{
			"pid":      node.Pid,
			"title":    node.Title,
			"image":    node.Image,
			"code":     node.Code,
			"level":    parent.Level + 1,
			"lib_type": node.LibType,
			"ordering": node.Ordering,
		})
		//go func(){
			//node.ReGenerateTestCategory()
		//}()
	}else{
		category := &models.Category{}
		newid ,err := category.Insert(node)
		beego.Warning(err)
		id = int(newid)
	}
	node.GetRealPath(id)
	res := map[string]interface{}{}
	res["id"] = id
	pcc.Single(res)
}


func (pcc *PointCategoryController) Option(){
	pcc.Fail("Options invoke","")
}

func (pcc *PointCategoryController) Regenerate(){
	cate := new(models.PqTestPointCategory)
	cate.ReGenerateTestCategory()
	pcc.Success("重置成功")
}